package com.aeye.mbr.upms.client.controller;

import com.aeye.mbr.cache.CacheClient;
import com.aeye.mbr.common.model.TreeNode;
import com.aeye.mbr.common.util.MultiKeyMap;
import com.aeye.mbr.upms.common.constant.UpmsCacheConstants;
import com.aeye.mbr.upms.dao.model.UpmsArea;
import com.aeye.mbr.upms.dao.model.UpmsDict;
import com.aeye.mbr.upms.dao.model.UpmsOrganization;
import com.aeye.mbr.upms.rpc.api.UpmsDictService;
import com.aeye.mbr.ws.util.JSONUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Created by shengpeng on 2018/3/26.
 * 各组件通用的Controller
 * 主要为前端公共组件提供数据
 * 数据来自于通用缓存组件
 */
@Controller
@RequestMapping(value="/common")
public class CommonController {
    static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @ResponseBody
    @RequestMapping(value = "/asyncAreaTree.html")
    public void asyncAreaTree(HttpServletRequest req, HttpServletResponse resp,
                              @RequestParam(value="level",required=false,defaultValue="5") int level,
                              @RequestParam(value="needRoot",required=false,defaultValue="0") int needRoot,
                              @RequestParam(value="id",required=false,defaultValue="000000000000") String id) {
        resp.setContentType("application/json;charset=UTF-8");
        String resultStr = "";

        MultiKeyMap<String,UpmsArea> areaMap = (MultiKeyMap<String, UpmsArea>) CacheClient.getCachedObject(UpmsCacheConstants.UPMS_AREA_CACHE);
        Collection<UpmsArea> children = areaMap.getByFKey(id);
        List<TreeNode> areas = new ArrayList<TreeNode>();
        for(UpmsArea child:children){
            TreeNode areaTree = new TreeNode();
            areaTree.setId(child.getId());
            areaTree.setPid(child.getPid());
            areaTree.setName(child.getName());
            areaTree.setLevel(child.getLevel());
            areaTree.setIsParent((child.getLevel() >= level || !areaMap.hasChildren(child.getId()))?false:true);
            areas.add(areaTree);
        }

        //如果是第一次加载，则将父节点加载进来，同时
        if(1==needRoot){
            UpmsArea child = areaMap.get(id);
            if(null != child){
                TreeNode areaTree = new TreeNode();
                areaTree.setId(child.getId());
                areaTree.setPid(child.getPid());
                areaTree.setName(child.getName());
                areaTree.setLevel(child.getLevel());
                areaTree.setIsParent(areas.size() > 0);
                areas.add(0,areaTree);
            }
        }
        resultStr = JSONUtils.toJSONString(areas);
        try {
            resp.getWriter().print(resultStr);
        } catch (IOException e) {
            log.error(e.getMessage() + e);
            try {
                resp.getWriter().print("[]");
            } catch (IOException e1) {
                log.error(e1.getMessage() + e1);
            }
        }
    }


    @ResponseBody
    @RequestMapping(value = "/asyncOrgTree.html")
    public void asyncOrgTree(HttpServletRequest req, HttpServletResponse resp,
                              @RequestParam(value="needRoot",required=false,defaultValue="0") int needRoot,
                              @RequestParam(value="id",required=false,defaultValue="0") String id) {
        resp.setContentType("application/json;charset=UTF-8");
        String resultStr = "";

        MultiKeyMap<String,UpmsOrganization> areaMap = (MultiKeyMap<String, UpmsOrganization>) CacheClient.getCachedObject(UpmsCacheConstants.UPMS_ORG_CACHE);
        Collection<UpmsOrganization> children = areaMap.getByFKey(id);
        List<TreeNode> areas = new ArrayList<TreeNode>();
        for(UpmsOrganization child:children){
            TreeNode areaTree = new TreeNode();
            areaTree.setId(String.valueOf(child.getOrganizationId()));
            areaTree.setPid(String.valueOf(child.getPid()));
            areaTree.setName(child.getName());
            areaTree.setIsParent((!areaMap.hasChildren(String.valueOf(child.getOrganizationId())))?false:true);
            areas.add(areaTree);
        }

        if(1==needRoot){
            UpmsOrganization child = areaMap.get(id);
            if(null != child){
                TreeNode areaTree = new TreeNode();
                areaTree.setId(String.valueOf(child.getOrganizationId()));
                areaTree.setPid(String.valueOf(child.getPid()));
                areaTree.setName(child.getName());
                areaTree.setIsParent(areas.size() > 0);
                areas.add(0,areaTree);
            }
        }
        resultStr = JSONUtils.toJSONString(areas);
        try {
            resp.getWriter().print(resultStr);
        } catch (IOException e) {
            log.error(e.getMessage() + e);
            try {
                resp.getWriter().print("[]");
            } catch (IOException e1) {
                log.error(e1.getMessage() + e1);
            }
        }
    }


    @RequestMapping(value = "/dictSelect", method = RequestMethod.GET)
    @ResponseBody
    public Object list2(String appFieldName) {
        UpmsDict dict = new UpmsDict();
        dict.setAppFieldName(appFieldName);
        List<UpmsDict> list = dictService.selectDictList(dict);
        return list;
    }

    @Autowired
    private UpmsDictService dictService;
}
